<template>
  <div class="editWedding">
    <h1 v-if="id">编辑儿童案例</h1>
    <h1 v-else>添加儿童案例</h1>
    <el-form ref="formline" class="box" :model="formline" :rules="rules">
      <el-form-item label="轮播图:" label-width="120px" prop="imagesData">
        <template slot-scope="scope">
          <form class="banner_loade" enctype="multipart/form-data">
            <el-button class="upload" type="primary ">
              添加多张图片
              <input class="file" type="file" name="file" @change="uploadImg($event)" />
            </el-button>
            <div class="loade_img" :class="{hide:formline.imagesData!=''}">
              <div
                style="position: relative;"
                v-for="(img,index) in formline.imagesData"
                :key="index"
              >
                <img class="img_auto" :src="img" alt />
                <i class="el-icon-error icon" @click="deleteImg(index)"></i>
              </div>
            </div>
          </form>
        </template>
      </el-form-item>

      <el-form-item label="案例名:" label-width="120px" prop="casename">
        <el-input v-model="formline.casename"></el-input>
      </el-form-item>
      <el-form-item label="标签:" label-width="120px" prop="dynamicTags">
        <el-tag
          :key="index"
          v-for="(tag,index) in formline.dynamicTags"
          closable
          :disable-transitions="false"
          @close="handleClose(index)"
        >{{tag}}</el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        ></el-input>
        <el-button class="button-new-tag" size="small" v-if="show" @click="showInput()">+标签</el-button>
      </el-form-item>
      <el-form-item label="拍摄/婚礼日期:" label-width="120px" prop="photoTime">
        <el-date-picker v-model="formline.photoTime" type="date" placeholder="选择日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="单价:" label-width="120px" prop="price">
        <el-input v-model="formline.price"></el-input>
      </el-form-item>
      <el-form-item label="图文介绍:" class="edit" label-width="120px">
        <div id="editorElem" style="width:55vw"></div>
      </el-form-item>

      <el-form-item align="center">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveInfo(formline)">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import uploadImgs from "../../unit/imgdata";
import E from "wangeditor";
import $ from "jquery";
import Qiniu from "../../../static/js/qiniu";
export default {
  data() {
    return {
      editorContent: "",
      formline: {
        imagesData: [],
        casename: "",
        photoTime: "",
        price: "",
        imgintro: "",
        dynamicTags: [] //标签
      },

      inputVisible: false,
      inputValue: "",
      show: true,
      id: "",
      rules: {
        imagesData: [
          {
            required: true,
            message: "请上传轮播图",
            trigger: "blur"
          }
        ],
        casename: [
          {
            required: true,
            message: "请输入案例名称",
            trigger: "blur"
          }
        ],
        photoTime: [
          {
            required: true,
            message: "请选择拍摄时间",
            trigger: "blur"
          }
        ],
        price: [
          {
            required: true,
            message: "请输入价格",
            trigger: "blur"
          }
        ],
        dynamicTags: [
          {
            required: true,
            message: "请添加标签",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    setTimeout(() => {
      this.wangeditor();
    }, 1000);
    let id = this.$route.query.infoId;
    this.id = this.$route.query.infoId;
    console.log(id);
    if (id) {
      //值不存在
      //值存在请求接口
      this.api
        .get("/api/studio", {
          id: id
        })
        .then(res => {
          console.log(res.data);
          let info = res.data;
          this.travel = res.data;
          this.formline.imagesData = info.photo;
          this.formline.dynamicTags = info.tag;
          this.formline.price = info.price;
          this.formline.casename = info.title;
          this.formline.photoTime = info.takeday;
          this.editorContent = info.descript;
        });
    }
  },
  methods: {
    cancel() {
      this.$router.go(-1);
    },
    wangeditor() {
      var editor = new E("#editorElem");
      editor.customConfig.onchange = html => {
        this.editorContent = html;
      };
      editor.customConfig.qiniu = true;
      editor.customConfig.pasteFilterStyle = false;
      editor.create();
      editor.txt.html(this.editorContent);
      console.log(this.editorContent, "内容 ");
      this.uploaderInit(editor);
    },
    blobToFile(dataurl, filename) {
      //base64位图片 转图片文件
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: mime
      });
    },
    imgPreview(file, dataInfo) {
      let self = this;
      // 判断是否支持FileReade
      if (!file || !window.FileReader) return;
      // 创建一个reader
      var reader = new FileReader();
      // 将图片转成base64格式
      reader.readAsDataURL(file);
      // 读取成功后的回调
      reader.onloadend = function() {
        let result = this.result;
        let img = new Image();
        img.src = result;
        console.log("============未压缩图片===========");
        console.log(result.length);
        img.onload = function() {
          let data = self.compress(img);
          console.log(data.length);
          self.imgUrl = result;
          var param = new FormData();
          let imgData = self.blobToFile(data, "ig1");
          console.log(data);
          param.append("files", imgData);
          self.api.post("/api/imgs", param).then(res => {
            dataInfo.push(res.data[0]);
          });
        };
      };
    },
    compress(img) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      canvas.width = width;
      canvas.height = height;
      // 铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, width, height);

      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.1);
      console.log("*******压缩后的图片大小*******");
      // console.log(ndata)
      console.log(ndata.length);
      return ndata;
    },
    uploadImg(e) {
      let that = this;
      let formData = new FormData();
      let reader = new FileReader();
      let imgName = e.target.files[0];
      reader.readAsDataURL(e.target.files[0]);
      that.imgPreview(imgName, that.formline.imagesData);
    },
    handleClose(index) {
      //删除标签
      this.formline.dynamicTags.splice(index, 1);
      if (this.formline.dynamicTags.length != 3) {
        this.show = true;
      }
    },
    showInput() {
      //添加标签
      if (this.formline.dynamicTags.length >= 3) {
        this.show = false;
        alert("标签最多添加三个");
      } else {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      }
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.formline.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    saveInfo() {
      //提交信息
      const _this = this;
      console.log(_this.editorContent, "werweeqqqqqqqqqqqqqqqqqqqq");
      var param = {
        photo: JSON.stringify(_this.formline.imagesData),
        price: _this.formline.price,
        tag: JSON.stringify(_this.formline.dynamicTags),
        takeday: _this.formline.photoTime,
        title: _this.formline.casename,
        descript: _this.editorContent
      };
      if (_this.id) {
        _this.$set(param, "id", _this.id);
        console.log(param);
        _this.api.post("/api/editstudio", param).then(res => {
          if (res.code == 200) {
            let info = res.data;
            _this.travel = res.data;
            _this.formline.imagesData = JSON.parse(info.photo);
            _this.formline.dynamicTags = JSON.parse(info.tag);
            _this.formline.price = info.price;
            _this.formline.casename = info.title;
            _this.formline.photoTime = info.takeday;
            _this.imgintro = info.descript;
            _this.$message({
              type: "success",
              message: "保存成功!"
            });
            setTimeout(function() {
              _this.$router.go(-1);
            }, 2000);
          }
        });
      } else {
        _this.api.post("/api/addstudio", param).then(res => {
          if (res.code == 200) {
            let info = res.data;
            _this.travel = res.data;
            _this.formline.imagesData = JSON.parse(info.photo);
            _this.formline.dynamicTags = JSON.parse(info.tag);
            _this.formline.price = info.price;
            _this.formline.casename = info.title;
            _this.formline.photoTime = info.takeday;
            _this.imgintro = info.descript;
            _this.$message({
              type: "success",
              message: "保存成功!"
            });
            setTimeout(function() {
              _this.$router.go(-1);
            }, 2000);
          }
        });
      }
    },
    deleteImg(index) {
      //删除图片
      this.formline.imagesData.splice(index, 1);
    },
    // 富文本
    uploaderInit(editor) {
      var that = this;
      var btnId = editor.imgMenuId;
      var containerId = editor.toolbarElemId;
      var textElemId = editor.textElemId;
      that.api.post("/api/uptoken", {}).then(res => {
        var uploader = new Qiniu().uploader({
          runtimes: "html5,flash,html4", //上传模式,依次退化
          browse_button: btnId, //上传选择的点选按钮，**必需**
          uptoken: res.data,
          unique_names: true,
          save_key: true,
          domain: "http://vrqn.liuliangin.com/", //bucket 域名，下载资源时用到，**必需**
          container: containerId, //上传区域DOM ID，默认是browser_button的父元素，
          max_file_size: "100mb", //最大文件体积限制
          filters: {
            mime_types: [
              //只允许上传图片文件 （注意，extensions中，逗号后面不要加空格）
              {
                title: "图片文件",
                extensions: "jpg,gif,png,bmp"
              }
            ]
          },
          max_retries: 3, //上传失败最大重试次数
          dragdrop: true, //开启可拖曳上传
          drop_element: textElemId, //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
          chunk_size: "4mb", //分块上传时，每片的体积
          auto_start: true, //选择文件后自动上传，若关闭需要自己绑定事件触发上传
          init: {
            FilesAdded: function(up, files) {
              plupload.each(files, function(file) {
                // 文件添加进队列后,处理相关的事情
                that.printLog("on FilesAdded");
              });
            },
            BeforeUpload: function(up, file) {
              // 每个文件上传前,处理相关的事情
              that.printLog("on BeforeUpload");
            },
            UploadProgress: function(up, file) {
              // 显示进度
              that.printLog("进度 " + file.percent);
            },
            FileUploaded: function(up, file, info) {
              // 每个文件上传成功后,处理相关的事情
              // 其中 info 是文件上传成功后，服务端返回的json，形式如
              // {
              //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
              //    "key": "gogopher.jpg"
              //  }
              that.printLog(info);
              // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
              var domain = up.getOption("domain");
              var res = $.parseJSON(info.response);
              var sourceLink = domain + res.key; //获取上传成功后的文件的Url
              that.printLog(sourceLink);
              // 插入图片到editor
              editor.cmd.do(
                "insertHtml",
                '<img src="' + sourceLink + '" style="max-width:100%;"/>'
              );
            },
            Error: function(up, err, errTip) {
              //上传出错时,处理相关的事情
              that.printLog("on Error");
            },
            UploadComplete: function() {
              //队列文件处理完毕后,处理相关的事情
              that.printLog("on UploadComplete");
            }
          }
          //upload的括号
        });
      });
    },
    printLog(title, info) {
      console.log(title, "1");
      console.log(info, "2");
      window.console && console.log(title, info);
    }
    // 富文本结束
  }
};
</script>

<style scoped>
.box {
  width: 50%;
}

.file {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 35px;
  line-height: 35px;
  text-align: center;
  opacity: 0;
}

.el-button {
  width: 100px;
}

.loade_img {
  background: url("./../../../static/img/push.jpg") no-repeat;
  background-size: 80px 80px;
  width: 100%;
  height: 80px;
  margin: 5px;
}

.loade_img div {
  margin: 5px;
  width: 80px;
  float: left;
}

.loade_img img {
  width: 80px;
  height: 80px;
}

.hide {
  background-image: none;
}

.img_auto {
  position: relative;
 max-width: 100%;
 width: 100%;
 max-height: 100%;
 height: 100%;
 object-fit: cover;
}

.icon {
  font-size: 25px;
  position: absolute;
  top: -8px;
  right: -8px;
}

.upload {
  position: relative;
  width: 120px;
  height: 35px;
}

/* 标签样式 */
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.edit >>> .el-form-item__content {
  z-index: 1;
}
</style>
